package com.l.web.util;

import com.l.web.WebConstant;
import com.l.web.master.system.config.Config;
import com.l.web.master.system.config.ConfigDAO;
import com.l.web.master.system.dictionary.DictionaryService;
import com.l.web.master.system.user.User;
import org.l.qiao.Cluster;
import org.l.qiao.util.ClusterUtil;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.ui.ModelMap;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * Created by yqw on 2016/10/23.
 */
public class ContextUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 获取spring容器的对象
     *
     * @param clazz
     * @param <T>
     * @return
     */
    protected <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    /**
     * SpringMvc下获取request
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

    /**
     * SpringMvc下获取session
     *
     * @return
     */
    public static HttpSession getSession() {
        HttpSession session = getRequest().getSession();
        return session;

    }

    /**
     * 获取当前登录用户
     *
     * @return
     */
    public static User getLoginUser() {
        HttpSession session = getSession();
        if (session != null) {
            User user = (User) session.getAttribute(WebConstant.SESSION_USER);
            if (user == null) {
                return null;
            }
            return user;
        }
        return null;
    }

    public static Config getConfigure(String key) {
        ConfigDAO configDAO = applicationContext.getBean(ConfigDAO.class);
        Cluster cluster = configDAO.getConfig(key);
        Config config = new Config((Map) WebConstant.config.clone());
        ClusterUtil.extend(config, cluster);
        return config;
    }

    public static void loadDictiondary(Map map, int... ids) {
        DictionaryService dictionaryService = applicationContext.getBean(DictionaryService.class);
        Map keys = dictionaryService.dictionarys(ids);
        map.put(WebConstant.CONTEXT_DICTIONARY, keys);
    }
}
